package com.example.testsbjenkins.jucTest;

import java.util.concurrent.Semaphore;

/**
 * @author: lt
 * @date: 2022/7/8 14:23
 * @Description: TestSemaphore 
 */
public class TestSemaphore {

    //模拟3个购票窗口  6个人买票场景
    static void test1() {
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < 6; i++) {
            int num = i + 1;
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + num + "获取到了购票资格");
                    Thread.sleep((long) (Math.random() * 1000));
                    System.out.println(Thread.currentThread().getName() + num + "买到了票");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
            }).start();

        }
        
        
        
        
            
        }
        

    
    public static void main(String[] args) {
        test1();
    }
}
